<template>
  <view class="certificate-container">
    <scroll-view 
      scroll-y 
      class="scrollable-content"
      :scroll-top="scrollTop"
      @scroll="onScroll"
      refresher-enabled
      @refresherrefresh="onRefresh"
      :refresher-triggered="isRefreshing"
    >
      <view class="page-header">
        <view class="header-title">我的证书</view>
        <view class="header-subtitle">查看和管理您的所有证书</view>
      </view>

      <view class="content-section">
        <view class="section-header">
          <view class="section-title">
            <view class="title-decoration"></view>
            <text>证书列表</text>
          </view>
        </view>

        <view class="certificate-list" v-if="certificateArr.length > 0">
          <view
            class="certificate-item"
            v-for="item in certificateArr"
            :key="item.certificateId"
            @click="goDetail(item.certificateId)"
          >
            <swiper
              class="certificate-swiper"
              indicator-dots
              indicator-color="rgba(255,255,255,0.3)"
              indicator-active-color="#fff"
              circular
              :autoplay="false"
              v-if="item.imageSrcs && item.imageSrcs.length > 1"
            >
              <swiper-item v-for="(src, index) in item.imageSrcs" :key="index">
                <image class="certificate-image" :src="src" mode="aspectFill" />
              </swiper-item>
            </swiper>
            <image
              v-else
              class="certificate-image"
              :src="item.imageSrcs[0]"
              mode="aspectFill"
            />
            <view class="certificate-overlay">
              <view class="certificate-view-text">查看详情</view>
              <view class="certificate-count" v-if="item.imageSrcs && item.imageSrcs.length > 1">
                <text>{{ item.imageSrcs.length }}张证书</text>
              </view>
            </view>
          </view>
        </view>
        <view class="empty-state" v-else>
          <text class="empty-text">暂无证书，请上传</text>
        </view>
      </view>
      
      <!-- 底部安全区域 -->
      <view class="bottom-space"></view>
    </scroll-view>

    <!-- 固定在底部的按钮 -->
    <view class="fixed-bottom" :class="{'fixed-bottom-shadow': showBottomShadow}">
      <button class="add-certificate-btn" @click="openUploadModal">+ 新增证书</button>
    </view>

    <uni-popup ref="uploadPopup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">新增证书</text>
          <text class="popup-close" @click="closeUploadModal">×</text>
        </view>
        
        <view class="popup-body">
          <view class="form-item">
            <text class="form-label">选择已购买课程：</text>
            <uni-data-select
              v-model="orderId"
              :localdata="orderArr"
              @change="changeOrder"
              class="custom-select"
              placeholder="请选择已购买课程"
            ></uni-data-select>
          </view>
          <view class="form-item">
            <text class="form-label">上传证书：</text>
            <view class="upload-container">
              <uni-file-picker
                ref="filePicker"
                v-model="imageValue"
                @select="selectPic"
                @delete="deleteImage"
                :disabled="!orderId"
                file-mediatype="image"
                limit="9"
                :auto-upload="false"
                mode="grid"
                :image-styles="imageStyles"
              >
                <view class="upload-btn" :class="{ 'upload-disabled': !orderId }" @click="onClick">
                  <view class="upload-icon">+</view>
                  <text class="upload-text">{{
                    !orderId ? "请先选择已购买课程" : "上传证书照片（可多选）"
                  }}</text>
                </view>
              </uni-file-picker>
            </view>
            <view class="upload-tips" v-if="imageValue.length > 0">
              <text>已选择 {{ imageValue.length }} 张照片</text>
              <text class="upload-tips-max">最多可上传9张</text>
            </view>
          </view>
        </view>
        
        <view class="popup-footer">
          <button class="cancel-btn" @click="closeUploadModal">取消</button>
          <button class="submit-btn" :disabled="!canSubmit" :class="{'submit-btn-active': canSubmit}" @click="submitCertificate">提交</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onBeforeMount, computed, onMounted } from "vue";
import { uploadImg, globalData } from "@/utils/util";
import api from "@/utils/api.js";
import { onShareAppMessage, onShareTimeline } from "@dcloudio/uni-app";

const imageValue = reactive([]);
const orderArr = ref([]);
const orderId = ref(0);
const certificateArr = ref([]);
const uploadPopup = ref(null);
const filePicker = ref(null);

// 新增的滚动相关变量
const scrollTop = ref(0);
const showBottomShadow = ref(false);
const isRefreshing = ref(false);

// 判断是否可以提交
const canSubmit = computed(() => {
  return orderId.value  && imageValue.length > 0;
});

// 打开上传弹窗
const openUploadModal = () => {
  // 重置表单
  resetForm();

  // 调用文件选择器的清除方法
  if (filePicker.value && filePicker.value.clearFiles) {
    filePicker.value.clearFiles();
  }
  uploadPopup.value.open();

  orderId.value = orderArr.value[0].value;

};

// 关闭上传弹窗
const closeUploadModal = () => {
  uploadPopup.value.close();
};

// 提交证书
const submitCertificate = async () => {
  if (!canSubmit.value) {
    uni.showToast({ title: "请先选择已购买课程并上传证书照片", icon: "none" });
    return;
  }
  
  // 处理多图上传
  const fileUrls = imageValue.map(item => {
    // 如果是字符串，直接返回
    if (typeof item === 'string') return item;
    // 否则从对象中获取url
    return item.url || item.tempFilePath || '';
  }).filter(url => url).join(',');
  
  if (!fileUrls) {
    uni.showToast({ title: "证书图片处理失败，请重新上传", icon: "none" });
    return;
  }
  
  uni.showLoading({ title: '提交中...' });
  
  api
    .certificateInfoAdd({ orderId: orderId.value, certificateUrl: fileUrls })
    .then((res) => {
      console.log(res,'res');
      if(res.code != 0){
        uni.hideLoading();
        uni.showToast({ title: res.msg, icon: "none" });
        return;
      }
      
      uni.hideLoading();
      uni.showToast({ title: "上传成功", icon: "success" });
      getcertificateList();
      // 重置表单并关闭弹窗
      resetForm();
      closeUploadModal();
    })
    .catch(err => {
      uni.hideLoading();
      uni.showToast({ title: "上传失败，请重试", icon: "none" });
    });
};

// 重置表单
const resetForm = () => {
  orderId.value = 0;
  imageValue.length = 0;
};

// 在script中添加imageStyles
const imageStyles = reactive({
  width: 140,
  height: 140,
  border: {
    radius: '8rpx'
  }
});

// 修改selectPic函数
const selectPic = async (e) => {
  // 添加新图片
  if (e.tempFiles && e.tempFiles.length > 0) {
    uni.showToast({ title: "上传中...", icon: "loading" });
    try {
      const results = await Promise.all(e.tempFiles.map(async (file) => {
        return await uploadImg(file);
      }));
      
      imageValue.push(...results);
      
      uni.hideToast();
      uni.showToast({ title: "已选择" + imageValue.length + "张图片", icon: "none" });
    } catch (error) {
      uni.hideToast();
      uni.showToast({ title: "上传失败，请重试", icon: "none" });
    }
  }
};

const onClick = () => {
  if (!orderId.value)
    return uni.showToast({ title: "请先选择已购买课程", icon: "none" });
};

const changeOrder = (e) => {
  console.log(e);
  orderId.value = e;
};

const getOrderList = async () => {
  await api.orderInfoList({ curPage: 1, pageSize: 20 }).then((res) => {
    orderArr.value = res.data?.itemLst?.map((item, index) => {
      return {
        text:
          item.userName +
          (index + 1) +
          " - " +
          (item.paymentStatus == 1 ? "已生效" : "未生效"),
        value: item.orderId,
        disable: item.paymentStatus != 1,
      };
    });
  });
};

const getcertificateList = async () => {
  return new Promise((resolve) => {
    api.certificateInfoList({ curPage: 1, pageSize: 9999999 }).then((res) => {
      certificateArr.value = (res.data?.itemLst || []).map(item => {
        return {
          ...item,
          imageSrcs: (item.certificateUrl?.split(',') || []).map(url => globalData.OSS_URL + url),
        };
      });
      imageValue.length = 0;
      resolve();
    }).catch(() => {
      resolve();
    });
  });
};

const goDetail = (certificateId) => {
  // 找到对应的证书对象
  const certificate = certificateArr.value.find(item => item.certificateId === certificateId);
  
  // 如果找到了证书对象，跳转到详情页并传递图片列表
  if (certificate) {
    uni.navigateTo({
      url: `/pages/certificateDetail/certificateDetail?certificateId=${certificateId}&imageUrls=${encodeURIComponent(JSON.stringify(certificate.imageSrcs))}`,
    });
  }
};

// 添加删除图片的处理函数
const deleteImage = (e) => {
  // 如果删除了所有图片，提示用户
  if (imageValue.length === 0) {
    uni.showToast({ title: "请至少上传一张证书照片", icon: "none" });
  }
};

// 滚动事件处理
const onScroll = (e) => {
  // 当滚动距离大于100时显示底部阴影
  showBottomShadow.value = e.detail.scrollTop > 100;
};

// 下拉刷新处理
const onRefresh = () => {
  isRefreshing.value = true;
  getcertificateList().then(() => {
    setTimeout(() => {
      isRefreshing.value = false;
    }, 500);
  });
};

onBeforeMount(() => {
  getOrderList();
  getcertificateList();
});

// 分享给朋友
onShareAppMessage(() => {
  return {
    title: '我的证书',
    path: '/pages/myCertificate/myCertificate'
  };
});

// 分享到朋友圈
onShareTimeline(() => {
  return {
    title: '我的证书',
    query: '' // 如果有参数可以带上
  };
});
</script>

<style lang="scss" scoped>
.certificate-container {
  background-color: #f6f8fa;
  height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.scrollable-content {
  flex: 1;
  height: 100%;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #f6f8fa;
  padding: 20rpx 0;
  padding-bottom: env(safe-area-inset-bottom, 40rpx); /* 适配底部安全区域 */
  z-index: 10;
  transition: box-shadow 0.3s ease;
}

.fixed-bottom-shadow {
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.bottom-space {
  height: calc(130rpx + env(safe-area-inset-bottom, 40rpx)); /* 调整底部安全距离 */
  width: 100%;
}

.page-header {
  background-color: #2cbaff;
  padding: 40rpx 40rpx 60rpx;
  color: #fff;
  position: relative;
  margin-bottom: 30rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.header-subtitle {
  font-size: 26rpx;
  opacity: 0.9;
}

.content-section {
  width: 92%;
  margin: 0 auto 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  margin-bottom: 30rpx;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.title-decoration {
  width: 8rpx;
  height: 32rpx;
  background-color: #2cbaff;
  border-radius: 4rpx;
  margin-right: 16rpx;
}

.certificate-list {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.certificate-item {
  position: relative;
  width: calc(50% - 20rpx);
  margin: 10rpx;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  background-color: #fff;
  transition: transform 0.3s;
  height: 320rpx;

  &:active {
    transform: scale(0.98);
  }
}

.certificate-swiper {
  width: 100%;
  height: 100%;
}

.certificate-image {
  width: 100%;
  height: 320rpx;
  display: block;
}

.certificate-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(44, 186, 255, 0.8);
  color: #fff;
  padding: 12rpx 0;
  text-align: center;
  font-size: 24rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.certificate-view-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #fff;
}

.certificate-count {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 22rpx;
  padding: 6rpx 16rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  
  &::before {
    content: '';
    width: 24rpx;
    height: 24rpx;
    background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="%23ffffff"><path d="M4 4h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zm0 2v8l4-3 4 3 4-3 4 3V6H4z"/></svg>');
    background-size: contain;
    margin-right: 8rpx;
  }
}

.empty-state {
  padding: 60rpx 0;
  text-align: center;
  color: #999;
}

.add-certificate-btn {
  width: 92%;
  height: 90rpx;
  margin: 0 auto;
  background-color: #2cbaff;
  color: #fff;
  border-radius: 45rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 12rpx rgba(44, 186, 255, 0.3);
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(44, 186, 255, 0.2);
  }
}

.popup-content {
  width: 650rpx;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.12);
}

.popup-header {
  position: relative;
  padding: 30rpx;
  background-color: #f8f8f8;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
}

.popup-close {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
  font-size: 40rpx;
  color: #999;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
}

.popup-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.upload-container {
  width: 100%;
}

.upload-btn {
  width: 100%;
  min-height: 200rpx;
  background-color: #f9f9f9;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #2cbaff;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
  padding: 20rpx;
  
  &:active {
    background-color: #edf8ff;
  }
  
  &.upload-disabled {
    color: #999;
    background-color: #f5f5f5;
    border-color: #eee;
  }
}

.upload-icon {
  font-size: 50rpx;
  margin-bottom: 10rpx;
}

.upload-text {
  font-size: 28rpx;
  text-align: center;
}

.upload-preview {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  padding: 10rpx;
  background-color: #f9f9f9;
}

.preview-image {
  width: 140rpx;
  height: 140rpx;
  margin: 10rpx;
  border-radius: 8rpx;
  object-fit: cover;
}

.popup-footer {
  display: flex;
  justify-content: space-between;
  padding: 20rpx 30rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn, .submit-btn {
  width: 45%;
  height: 80rpx;
  border-radius: 40rpx;
  font-size: 30rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1rpx solid #eee;
}

.submit-btn {
  background-color: #ccecff;
  color: rgba(255, 255, 255, 0.9);
  
  &.submit-btn-active {
    background-color: #2cbaff;
    color: #fff;
  }
  
  &:disabled {
    background-color: #ccecff;
    color: rgba(255, 255, 255, 0.9);
  }
}

:deep(.uni-data-select) {
  border: 1px solid #eaeaea;
  border-radius: 8rpx;

  .uni-select__input-text {
    font-size: 28rpx;
  }
}

:deep(.uni-file-picker__container) {
  width: 100% !important;
}

:deep(.uni-file-picker__upload) {
  display: none;
}

.upload-tips {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #666;
  display: flex;
  justify-content: space-between;
}

.upload-tips-max {
  color: #999;
}

/* 确保弹窗能够正常显示在固定底部之上 */
:deep(.uni-popup) {
  z-index: 999;
}

:deep(.uni-popup__wrapper) {
  z-index: 1000;
}
</style>
